# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)

#
# WARNING: DO NOT EDIT THIS FILE MANUALLY - IT IS AUTOMATICALLY GENERATED BY THE PLUGIN
#
module SyncsHelper
  module Misc
    private
    
    # Assumes the existence of a User model binded to the Replica model
    # the same way UserStamp works
    def current_client
      @current_client ||= Replica.user_model.find(session[:user])
      @current_client
    end
  
    # This is used in the 'server' end of the communication, where a server
    # can serve lots of 'clients', each one registered with a unique
    # identifier in the RemoteClient table
    def current_remote_client
      return nil unless session[:client_id]
      @remote_client ||= RemoteClient.find_by_client_id(session[:client_id])
      @remote_client
    end
  
    # The server logs in when was the last time it received data
    # from a specific client. It send this time back after the
    # next successful authentication handshake
    def stamp_sync_remote_user(t)
      machine = RemoteMachine.find(session[:machine].id)
      machine.last_synced = t || -1
      machine.update
    rescue => e
      raise "Error assigning new last_synced timestamp. #{e.inspect}"
    end
  
    # This pre-loads the models so YAML deserialization finds the correct classes
    # but still dunno why this is required. If don't used YAML will deserialize
    # model objects as YAML::Object instances
    def fix_model_loading
      # TODO: trying a new fix upon the init.rb
      # if doesn't work, uncomment this line
      # Dir.new(File.join(RAILS_ROOT, 'app', 'models')).each { |s| require s if s =~ /\.rb$/ }
    end
  
    # Helper to build the HTTP address through the $SYNC_CONFIG parameters
    def address
      "#{$SYNC_CONFIG[:protocol]}://#{$SYNC_CONFIG[:hostname]}:#{$SYNC_CONFIG[:port]}"
    end
  end
end